import { topMessage } from '@/components/TopMessage/data'
import { loading, makeErrMsg } from './message'
import { fillInFriend, userInfoFull } from './user'

/**
 * 捕获错误通用模板
 * @param execute 执行函数
 * @param o 自定义参数
 */
export const catchFn = async (
  execute: () => Promise<any>,
  o: {
    /** 是否禁用加载 */
    disableLoading?: boolean
    /** 是否禁用提示 */
    disableTips?: boolean
    /** 报错回调 */
    onError?: (err: any) => any
  } = {},
) => {
  const tip = !o.disableTips
  const l = !o.disableLoading

  try {
    l && loading(true)
    return await execute()
  } catch (err) {
    o.onError?.(err)
    tip && topMessage.error(makeErrMsg(err))
  } finally {
    l && loading(false)
  }
}

/**
 * 返回
 * @param target 目标页面
 */
export const back = (target?: string) => {
  const pages = getCurrentPages()

  if (target) {
    const idx = pages.findIndex(item => item.route && target.includes(item.route))

    ~idx
      ? uni.navigateBack({
          delta: pages.length - 1 - idx,
          fail: () => uni.reLaunch({ url: target }),
        })
      : uni.reLaunch({ url: target })
  } else {
    const url = userInfoFull.value ? '/pages/main/index' : '/pages/user/edit-info/index'

    pages.length > 1
      ? uni.navigateBack({
          fail: () => uni.reLaunch({ url }),
        })
      : uni.reLaunch({ url })
  }
}

/**
 * 返回主页
 */
export const backToMain = () =>
  new Promise<void>(resolve => {
    const pages = getCurrentPages()
    const url =
      fillInFriend.value || !userInfoFull.value
        ? '/pages/user/edit-info/index'
        : '/pages/main/index'

    url === (pages[0]?.route || '')
      ? pages.length > 1
        ? uni.navigateBack({
            delta: pages.length - 1,
            success: resolve,
          })
        : resolve()
      : uni.reLaunch({ url, success: resolve })
  })

/**
 * 等待
 * @param duration 时长
 */
export const wait = (duration: number) => new Promise(resolve => setTimeout(resolve, duration))

/**
 * 版本号比对
 * @param v1
 * @param v2
 */
export const compareVersion = (v1: string, v2: string) => {
  const v1Arr = v1.split('.')
  const v2Arr = v2.split('.')
  const len = Math.max(v1Arr.length, v2Arr.length)

  while (v1Arr.length < len) {
    v1Arr.push('0')
  }
  while (v2Arr.length < len) {
    v2Arr.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1Arr[i])
    const num2 = parseInt(v2Arr[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

/**
 * 获取日期
 */
export const getDate = (addY = 0) => {
  const date = new Date()
  const year = date.getFullYear() + addY
  const month = date.getMonth() + 1
  const day = date.getDate()

  return `${year}-${month > 9 ? month : '0' + month}-${day > 9 ? day : '0' + day}`
}
